/**
 * 
 */
package com.zxc.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @author Administrator
 *
 */
public class FileChannelDemo {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile("D:/test.txt", "rw");
		FileChannel inChannel = aFile.getChannel();
		
		String content = "";
		
		Charset charset = Charset.forName("UTF-8");
		CharsetDecoder decoder = charset.newDecoder();
		
		ByteBuffer buf = ByteBuffer.allocate((int)aFile.length());
		CharBuffer cb = CharBuffer.allocate((int)aFile.length());
		int bytesRead = inChannel.read(buf);
		while (bytesRead != -1) {

			System.out.println("Read " + bytesRead);
			buf.flip();
			
			decoder.decode(buf,cb,false);
			cb.flip();
			
			content+=new String(cb.array());
			
//			while (buf.hasRemaining()) {
//				System.out.print((char) buf.get());
//			}

			buf.clear();
			bytesRead = inChannel.read(buf);
		}
		
		ByteBuffer src = ByteBuffer.wrap(content.getBytes("UTF-8"));
		
		inChannel.write(src);
		aFile.close();
	}

}
